<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>开始比赛</title>
    <link rel="stylesheet" href="../utils/bootstrap-5.3.3-dist/css/bootstrap.min.css">
    <script src="../utils/bootstrap-5.3.3-dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../utils/icon/iconfont.css">
    <link rel="stylesheet" href="../css/shared.css">
    <style>
        /*中部布局*/
        .central-layout {
            display: grid;
            grid-template-rows: 40px 550px;
            width: 100%;
            margin: 0 auto;
        }

        /*中部底部布局*/
        .central-bottom-layout {
            display: grid;
            grid-template-columns: 2.5fr 7.5fr;
            width: 100%;
        }

        /*中部顶部*/
        .central-top {
            margin-left: 50px;
            font-weight: bold;
        }

        /*中部底部右部分布局*/
        .c-b-right-layout {
            display: grid;
            grid-template-rows: 50px 450px 50px;
            width: 98%;
            margin: 0 auto;
        }

        /*中部底部左部分布局*/
        .c-b-left-layout {
            border: 1px solid black;
            display: grid;
            height: 550px;
            grid-template-rows: auto 1fr;
            margin-left: 20px;
            padding: 10px;
        }

        /*中部底部右部分头部布局*/
        .c-b-r-head {
            display: flex;
            flex-direction: row;
            align-items: center;
            gap: 10px;
            padding: 5px;
            justify-content: space-evenly;
        }

        .details-title {
            border-bottom: 1px solid black;
            font-size: large;
            font-weight: bold;
            text-align: center;
        }

        .details-body {
            overflow-y: auto;
        }

        .details-elements {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }


        /*表项限宽*/
        #person-detail-table td {
            max-width: 7vw;
        }

        #relay-detail-table td {
            max-width: 7vw;
        }

        #relay-team-table td {
            max-width: 6vw;
        }

        #person-table td {
            max-width: 8vw;
        }

        #relay-table td {
            max-width: 10vw;
        }
    </style>
</head>

<body>
    <div class="body-grid">
        <!--头部-->
        <div class="header-grid">
            <!--    返回按钮-->
            <div>
                <!--            <button class="btn btn-secondary iconfont go-back-button" onclick="window.location.href='card-issuance.html';">-->
                <!--                &#xe623;-->
                <!--            </button>-->
            </div>
            <!--    标题-->
            <div class="page-title" id="page-title">
                <script>
                    document.getElementById("page-title").innerText=window.sessionStorage.getItem("competitionName")
                    +"--开始比赛"
                </script>
            </div>
            <div></div>
        </div>
        <!--中部-->
        <div class="central-layout">
            <div>
                <!--        顶部导航-->
                <div class="btn-group">
                    <button type="button" class="btn btn-primary" onclick="window.location.href='batch.html'">批次管理
                    </button>
                    <button type="button" class="btn btn-primary" onclick="window.location.href='rule.html'">规则设置
                    </button>
                    <button type="button" class="btn btn-primary" onclick="window.location.href='start-game.html'">
                        开始比赛
                    </button>
                    <button type="button" class="btn btn-primary" onclick="window.location.href='calculate-score.html'">
                        成绩计算
                    </button>
                    <button type="button" class="btn btn-primary" onclick="window.location.href='replace-card.html'">补卡
                    </button>
                </div>
                <span class="central-top" id="project-name-id">比赛项目:</span>
                <span class="central-top" id="project-time-id">比赛时间:</span>
                <span class="central-top" id="total-number-id">总数:</span>
            </div>
            <div class="central-bottom-layout">
                <div class="c-b-left-layout">
                    <div class="details-title">
                        打卡详情
                        <button id="pGrade" disabled type="button" class="btn btn-sm btn-primary " onclick="printGrade()" style="position:relative; top:-5px; float: right;">打印小票
                        </button>
                    </div>
                    <div class="details-body">
                        <div id="personDetails" class="details-elements" style="display: none;">
                            <div>
                                姓名：<span id="detailName"></span>
                            </div>
                            <div>
                                指卡号：<span id="detailCard"></span>
                            </div>
                            <div>
                                选手号码：<span id="detailNumber"></span>
                            </div>
                            <div>
                                组别：<span id="detailGroup"></span>
                            </div>
                            <div>
                                参赛单位：<span id="detailUnit"></span>
                            </div>

                            <div>
                                电话：<span id="detailPhone"></span>
                            </div>
                            <div>
                                打卡路线：<span id="detailRoute"></span>
                            </div>
                            <div>
                                用时：<span id="detailTime"></span>
                            </div>
                            <div>
                                <b>详情</b>
                            </div>
                            <div class="table-responsive">
                                <table id="person-detail-table" class="table table-sm table-bordered text-center">
                                    <thead>
                                        <tr>
                                            <th>站号</th>
                                            <th>打卡时间</th>
                                        </tr>

                                    </thead>
                                    <tbody id="person-detail-tbody" class="table-group-divider">

                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div id="teamDetails" class="details-elements" style="display:none;">
                            <div>
                                接力队伍：<span id="teamDetailName"></span>
                            </div>
                            <div>
                                组别：<span id="teamDetailGroup"></span>
                            </div>

                            <div>
                                参赛单位：<span id="teamDetailUnit"></span>
                            </div>

                            <div>
                                单位电话：<span id="teamDetailPhone"></span>
                            </div>

                            <div>
                                打卡路线：<span id="teamDetailRoute"></span>
                            </div>

                            <div>
                                用时：<span id="teamDetailTime"></span>
                            </div>

                            <div>
                                <b>详情</b>
                            </div>
                            <div class="table-responsive">
                                <table id="relay-detail-table" class="table table-sm table-bordered text-center">
                                    <thead>
                                        <tr>
                                            <th>站号</th>
                                            <th>打卡时间</th>
                                        </tr>
                                    </thead>
                                    <tbody id="relay-detail-tbody" class="table-group-divider">
                                    </tbody>
                                </table>
                            </div>
                            <div>
                                <b>接力人员：</b>
                            </div>
                            <div class="table-responsive">
                                <table id="relay-team-table" class="table table-sm table-bordered text-center">
                                    <thead>
                                        <tr>
                                            <th>姓名</th>
                                            <th>指卡号</th>
                                            <th>选手号码</th>
                                            <th>批次</th>
                                        </tr>
                                    </thead>
                                    <tbody id="relay-team-tbody" class="table-group-divider">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="c-b-right-layout">
                    <div class="c-b-r-head">
                        <label>
                            组别：
                            <select id="group-search" onchange="showSearch()">
                                <option value="">全部</option>
                            </select>
                        </label>
                        <label>
                            打终点站：
                            <select id="Terminal" onchange="showSearch()">
                                <option value="">全部</option>
                                <option value="true">已打终点站</option>
                                <option value="false">未打终点站</option>
                            </select>
                        </label>
                        <div>
                            <button id="makeCardBtn" class="btn btn-primary" onclick="websocketConnect()">
                                开始录入
                            </button>
                            <span id="makeCardMsg2" style="margin-left:10px;color:red;display:none;">请连接读卡器设备</span>
                            <span id="makeCardMsg" style="margin-left:10px;color:red;display:none;">请放置指卡</span>
                        </div>

                    </div>
                    <div class="table-responsive">
                        <table id="person-table" class="table table-sm table-bordered text-center"
                            style="display: none">
                            <thead>
                                <tr>
                                    <th>操作</th>
                                    <th>选手号码</th>
                                    <th>指卡号</th>
                                    <th>组别</th>
                                    <th>姓名</th>
                                    <th>选手电话</th>
                                    <th>单位电话</th>
                                    <th>参赛单位</th>
                                    <th>路线</th>
                                    <th>用时</th>
                                </tr>
                            </thead>
                            <tbody id="person-tbody" class="table-group-divider">
                            </tbody>
                        </table>
                        <table id="relay-table" class="table table-sm table-bordered text-center" style="display: none">
                            <thead>
                                <tr>
                                    <th>操作</th>
                                    <th>接力队伍</th>
                                    <th>组别</th>
                                    <th>参赛单位</th>
                                    <th>单位电话</th>
                                    <th>路线</th>
                                    <th>用时</th>
                                </tr>
                            </thead>
                            <tbody id="relay-tbody" class="table-group-divider">
                            </tbody>
                        </table>
                    </div>
                    <div>
                        <!--    分页组件-->
                        <ul class="pagination page-ul-flex" id="pagination">
                        </ul>
                    </div>
                </div>

            </div>

        </div>
        <!--尾部-->
        <div class="footer-grid">
            <!--网格留空-->
            <div></div>
            <!--进度条-->
            <div id="progress-bar" class="progress-bar-flex">
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">新增赛事</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">新增项目</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">设置组别</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">导入选手</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">下发号码</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">制卡</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">签到</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">批次管理</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">规则设置</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">开始比赛</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">成绩计算</div>
                    <i class="iconfont progress-bar-arrow" style="visibility: hidden;">&#xe604;</i>
                </div>
            </div>
            <!--   占位不能删-->
            <div>
            </div>
        </div>
    </div>
    <script src="../js/pages.js"></script>
    <script src="../api/urls.js"></script>
    <script src="../js/dialog.js"></script>
    <script src="../js/progress.js"></script>
    <script src="../js/request.js"></script>
    <script>
        updateProgress("progress-bar", START_GAME_PROGRESS);
        //页码
        let pageNum = 1;
        //一页多少条
        let pageSize = 20;
        //总条数
        let total;
        //总页数
        let pages;
        //请求记录
        let records;
        let project = null;
        //当前项目id
        let projectId = null;
        //点击的指卡id
        let cardId = null;
        //是否是接力
        let isRelay;
         //接力队伍id
         let teamId;
         //未打终点站
         let unTerminal;

        window.onload = async function () {
            //每次刷新页面必须关闭串口，以防之前打开的串口未被关闭
            await closePort()
        }

        async function getRecentProject() {
            let url = new URL(PROJECT_URL + "/getRecentProject");
            url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
            await fetch(url).then(res => res.json())
                .then(result => {
                    projectId = result.projectId;
                    isRelay = result.isRelay;
                    let name = document.getElementById("project-name-id");
                    name.textContent = "比赛项目：" + result.projectName;
                    project=result.projectName;
                    let startTime = document.getElementById("project-time-id");
                    if (result.startTime) {
                        startTime.textContent = "比赛时间：" + result.startTime.split("T")[0] + " " + result.startTime.split("T")[1];
                    }
                    unTerminal = result.unTerminal

                    if(result.unTerminal<=0){
                        document.getElementById("makeCardBtn").disabled =true
                        
                    }else{
                        document.getElementById("makeCardBtn").disabled =false
                    }

                    let total = document.getElementById("total-number-id");
                    total.textContent = "总数：" + result.total + " 已打终点站：" + result.hasTerminal + " 未打终点站：" + result.unTerminal
                });
            console.log(projectId)
        }

        /**
         * 开始录入逻辑
         */
        function startInput() {
            let start = document.getElementById("start-input");
            let end = document.getElementById("end-input");
            let prompt = document.getElementById("prompt");
            start.style.display = "none";
            end.style.removeProperty("display");
            prompt.style.visibility = "visible";
        }

        /**
         * 结束录入逻辑
         */
        function endInput() {
            let start = document.getElementById("start-input");
            let end = document.getElementById("end-input");
            let prompt = document.getElementById("prompt");
            end.style.display = "none";
            start.style.removeProperty("display");
            prompt.style.visibility = "hidden";
        }

        /**
         *获取项目下拉菜单
         */
        async function getGroupMenu() {

            let url = new URL(GROUP_URL + GET_URL);
            url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
            await fetch(url).then(r => {
                return r.json();
            }).then(result => {
                let groupSearch = document.getElementById("group-search");
                for (const projectMenu of result) {
                    let option = document.createElement("option");
                    option.value = projectMenu.id;
                    option.textContent = projectMenu.name;
                    groupSearch.append(option);
                }
            });
        }
        /**
         * 点击搜索
         */
        async function showSearch() {
            pageNum = 1;
            await showPage();
        }

        /**
         * 渲染表格
         */
        function drawGradeTable(records) {
            let personTable = document.getElementById("person-table"); //个人赛表格
            let relayTable = document.getElementById("relay-table"); //接力赛赛表格

            let personDetails = document.getElementById("personDetails"); //个人赛打卡详情
            let teamDetails = document.getElementById("teamDetails"); //接力赛打卡详情
            
            if (isRelay) {
                
                personTable.style.display = "none";
                personDetails.style.display = "none";

                relayTable.style.removeProperty("display");
                teamDetails.style.removeProperty("display");

                let tableBody = document.getElementById("relay-tbody");
                tableBody.innerHTML = "";
                for (let record of records) {
                    let trElement = document.createElement("tr");
                    let tdElement1 = document.createElement("td");
                    let buttonElement1 = document.createElement("button");
                    buttonElement1.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
                    buttonElement1.textContent = "详情";

                    buttonElement1.addEventListener("click", async () => {

                        let btn=document.getElementById('pGrade').disabled='' //打开打印按钮

                        document.getElementById("teamDetailName").innerText = record.teamName
                        document.getElementById("teamDetailGroup").innerText = record.groupName
                        document.getElementById("teamDetailUnit").innerText = record.unitName
                        document.getElementById("teamDetailPhone").innerText = record.unitPhone
                        document.getElementById("teamDetailRoute").innerText = record.route
                        document.getElementById("teamDetailTime").innerText = record.time

                        //查询接力队伍的打卡路线
                        let urlT = new URL(BASE_URL+'/details/getDetailsByGId')
                        urlT.searchParams.set("gradeId", record.gradeId)
                        let resT = await fetch_http({
                            url: urlT,
                            method: 'get'
                        })
                        document.getElementById('relay-detail-tbody').innerHTML = ''
                        if (resT.code == 200 && resT.data.length) {
                            for (let i = 0; i < resT.data.length; i++) {
                                let trElement = document.createElement("tr");
                                let tdElement1 = document.createElement("td");
                                let tdElement2 = document.createElement("td");
                                if (resT.data[i].stationNumber == 0) {
                                    tdElement1.innerText = '起点'
                                }else if (resT.data[i].stationNumber >=1 && resT.data[i].stationNumber <=10 ) {
                                    tdElement1.innerText = resT.data[i].stationNumber
                                }else if (resT.data[i].stationNumber >=11 && resT.data[i].stationNumber <=15 ) {
                                    tdElement1.innerText = 'F'+resT.data[i].stationNumber%10
                                }else if (resT.data[i].stationNumber == 19) {
                                    tdElement1.innerText = 'S'
                                }
                                else if (resT.data[i].stationNumber == 20) {
                                    tdElement1.innerText = 'MO'
                                }
                                else if (resT.data[i].stationNumber == 99) {
                                    tdElement1.innerText = '终点'
                                }
                                resT.data[i].clockTime.split('T')

                                tdElement2.innerText = resT.data[i].clockTime.split('T')[0] + " " + resT.data[i].clockTime.split('T')[1]
                                trElement.appendChild(tdElement1)
                                trElement.appendChild(tdElement2)
                                document.getElementById('relay-detail-tbody').appendChild(trElement)
                            }
                        }
                        

                        teamId=record.teamId
                        //查询队伍的接力人员
                        let url = new URL(BASE_URL+'/team/selectAtheleByTId')
                        url.searchParams.set("teamId", record.teamId)
                        url.searchParams.set("projectId", projectId)
                        let res = await fetch_http({
                            url: url,
                            method: 'get'
                        });

                       

                        document.getElementById('relay-team-tbody').innerHTML = ''
                        if (res.code == 200 && res.data.length) {
                            for (let i = 0; i < res.data.length; i++) {
                                let trElement = document.createElement("tr");
                                let tdElement1 = document.createElement("td");
                                let tdElement2 = document.createElement("td");
                                let tdElement3 = document.createElement("td");
                                let tdElement4 = document.createElement("td");
                                tdElement1.innerText = res.data[i].name;
                                tdElement2.innerText = res.data[i].tpCard;
                                tdElement3.innerText = res.data[i].number;
                                tdElement4.innerText = res.data[i].sequence;
                                trElement.appendChild(tdElement1)
                                trElement.appendChild(tdElement2)
                                trElement.appendChild(tdElement3)
                                trElement.appendChild(tdElement4)
                                document.getElementById('relay-team-tbody').appendChild(trElement)
                            }
                        }
                    });

                    tdElement1.append(buttonElement1);
                    let tdElement2 = document.createElement("td");
                    tdElement2.textContent = record.teamName;
                    let tdElement3 = document.createElement("td");
                    tdElement3.textContent = record.groupName;
                    let tdElement4 = document.createElement("td");
                    tdElement4.textContent = record.unitName;
                    let tdElement5 = document.createElement("td");
                    tdElement5.textContent = record.unitPhone;
                    let tdElement6 = document.createElement("td");
                    tdElement6.textContent = record.route;
                    let tdElement7 = document.createElement("td");
                    tdElement7.textContent = record.time;

                    trElement.append(tdElement1, tdElement2, tdElement3, tdElement4, tdElement5, tdElement6, tdElement7);
                    tableBody.append(trElement);
                }
            } else {
                relayTable.style.display = "none";
                teamDetails.style.display = "none";

                personTable.style.removeProperty("display");
                personDetails.style.removeProperty("display");

                let tableBody = document.getElementById("person-tbody");
                tableBody.innerHTML = "";
                for (let record of records) {
                    let trElement = document.createElement("tr");
                    let tdElement1 = document.createElement("td");
                    let buttonElement1 = document.createElement("button");
                    buttonElement1.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
                    buttonElement1.textContent = "详情";
                    buttonElement1.addEventListener("click", async () => {

                        let btn=document.getElementById('pGrade').disabled='' //打开打印按钮

                        document.getElementById("detailName").innerText = record.name
                        document.getElementById("detailCard").innerText = record.card
                        document.getElementById("detailNumber").innerText = record.number
                        document.getElementById("detailGroup").innerText = record.group
                        document.getElementById("detailUnit").innerText = record.unit
                        if (record.unit == '无单位') {
                            document.getElementById("detailPhone").innerText = record.phone
                        } else {
                            document.getElementById("detailPhone").innerText = record.unitPhone
                        }
                        document.getElementById("detailRoute").innerText = record.route
                        document.getElementById("detailTime").innerText = record.time
                        cardId=record.cardId


                        let url = new URL(BASE_URL+'/details/getDetailsByGId')
                        url.searchParams.set("gradeId", record.gradeId)
                        let res = await fetch_http({
                            url: url,
                            method: 'get'
                        })
                        document.getElementById('person-detail-tbody').innerHTML = ''
                        if (res.code == 200 && res.data.length) {
                            for (let i = 0; i < res.data.length; i++) {
                                let trElement = document.createElement("tr");
                                let tdElement1 = document.createElement("td");
                                let tdElement2 = document.createElement("td");
                                if (res.data[i].stationNumber == 0) {
                                    tdElement1.innerText = '起点'
                                } else if (res.data[i].stationNumber >=1 && res.data[i].stationNumber <=10 ) {
                                    tdElement1.innerText = res.data[i].stationNumber
                                }else if (res.data[i].stationNumber >=11 && res.data[i].stationNumber <=15 ) {
                                    tdElement1.innerText = 'F'+res.data[i].stationNumber%10
                                }else if (res.data[i].stationNumber == 19) {
                                    tdElement1.innerText = 'S'
                                }
                                else if (res.data[i].stationNumber == 20) {
                                    tdElement1.innerText = 'MO'
                                }
                                else if (res.data[i].stationNumber == 99) {
                                    tdElement1.innerText = '终点'
                                }
                                res.data[i].clockTime.split('T')

                                tdElement2.innerText = res.data[i].clockTime.split('T')[0] + " " + res.data[i].clockTime.split('T')[1]
                                trElement.appendChild(tdElement1)
                                trElement.appendChild(tdElement2)
                                document.getElementById('person-detail-tbody').appendChild(trElement)
                            }
                        }
                    });
                    tdElement1.append(buttonElement1);
                    let tdElement2 = document.createElement("td");
                    tdElement2.textContent = record.number;
                    let tdElement3 = document.createElement("td");
                    tdElement3.textContent = record.card;
                    let tdElement4 = document.createElement("td");
                    tdElement4.textContent = record.group;
                    let tdElement5 = document.createElement("td");
                    tdElement5.textContent = record.name;
                    let tdElement6 = document.createElement("td");
                    tdElement6.textContent = record.phone;
                    let tdElement7 = document.createElement("td");
                    tdElement7.textContent = record.unitPhone;
                    let tdElement8 = document.createElement("td");
                    tdElement8.textContent = record.unit;
                    let tdElement9 = document.createElement("td");
                    tdElement9.textContent = record.route;
                    let tdElement10 = document.createElement("td");
                    tdElement10.textContent = record.time;
                    trElement.append(tdElement1, tdElement2, tdElement3, tdElement4, tdElement5, tdElement6,
                        tdElement7, tdElement8, tdElement9, tdElement10);
                    tableBody.append(trElement);
                }
            }

        }

        //实现分页的方法
        async function getPage(pageNum, pageSize) {
            let url;
            if (isRelay) {
                url = new URL(GRADE_URL + "/startGameSearchAllRelay");
            } else {
                url = new URL(GRADE_URL + "/startGameSearchAllPerson");
            }
            url.searchParams.set("pageNum", pageNum);
            url.searchParams.set("pageSize", pageSize);
            url.searchParams.set("projectId", projectId);
            let groupSearch = document.getElementById("group-search");
            let isTerminal = document.getElementById("Terminal");
            if (groupSearch.value) {
                url.searchParams.set("groupId", groupSearch.value);
            }
            if (isTerminal.value) {
                url.searchParams.set("isTerminal", isTerminal.value);
            }
            await fetch(url).then(response => {
                if (response.ok && response.headers.get("Content-Type") === "application/json") {
                    return response.json();
                } else {
                    throw new Error(`未知相应状态 ${response.status}或Content-Type：${response.headers.get("Content-Type")}`);
                }
            }).then(pageInfo => {
                pages = pageInfo.pages;
                total = pageInfo.total;
                records = pageInfo.records;
                drawGradeTable(records);
            }).catch(error => {
                console.log("分页错误：", error);
            });
        }

        //上一页
        async function prePage() {
            pageNum = pageNum - 1;
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }

        //下一页
        async function nextPage() {
            pageNum = pageNum + 1;
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages)
        }

        //点击切换
        async function handlePage(page) {
            if (page !== pageNum) {
                pageNum = page
                await getPage(pageNum, pageSize);
                createpage(pageNum, pageSize, total, pages);
            }

        }

        /**
         * 改变每页条数
         */
        async function changePageSize(value) {
            pageSize = Number(value);
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }

        // 创建分页组件
        async function showPage() {
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }


        if (window.sessionStorage.getItem("competitionId")) {
            (async () => {
                await getRecentProject();
                await getGroupMenu();
                if (projectId) {
                    await showPage();
                }
            })();
        }


        //通过websocket来录入选手成绩
        function websocketConnect() {
            const ws_url = WEBSOCKET_BASE_URL + projectId;
            socket = new WebSocket(ws_url)

            socket.onopen = async function () {
                var makeCardBtn = document.getElementById('makeCardBtn')
                var makeCardMsg = document.getElementById('makeCardMsg')
                var makeCardMsg2 = document.getElementById('makeCardMsg2')

                let res = await openPort()
                console.log(res)
                if (res.code !== '200') {
                    //断开连接并关闭串口
                    await socket.close()
                    makeCardMsg2.style.display = ''

                } else {
                    makeCardBtn.onclick = closeWebsocket
                    makeCardBtn.innerText = "结束录入"
                    makeCardBtn.className = "btn btn-danger"
                    makeCardMsg.style.display = ''
                    makeCardMsg.innerText = '请放置指卡'
                    makeCardMsg2.style.display = 'none'
                }

            }

            socket.onmessage = async function (event) {

                if (event.data === '读卡结束......') {
                    await showPage();
                    await getRecentProject();
                    
                }

                if (event.data.substring(0, 5) == '成绩id:') {
					let btn=document.getElementById('pGrade').disabled='true'
                    if (isRelay) {
                        //查询队伍信息
                        let url1 = new URL(BASE_URL+'/grade/startGameSearchOnlyTeam')
                        url1.searchParams.set("gradeId", event.data.split('接力队伍id:')[0].substring(5, event.data.split('接力队伍id:')[0].length))
                        let res1 = await fetch_http({
                            url: url1,
                            method: 'get'
                        })

                        document.getElementById("teamDetailName").innerText = res1.data.teamName
                        document.getElementById("teamDetailGroup").innerText = res1.data.groupName
                        document.getElementById("teamDetailUnit").innerText = res1.data.unitName
                        document.getElementById("teamDetailPhone").innerText = res1.data.unitPhone
                        document.getElementById("teamDetailRoute").innerText = res1.data.route
                        document.getElementById("teamDetailTime").innerText = res1.data.time

                        //查询接力队伍的打卡路线
                        let urlT = new URL(BASE_URL+'/details/getDetailsByGId')
                        urlT.searchParams.set("gradeId", event.data.split('接力队伍id:')[0].substring(5, event.data.split('接力队伍id:')[0].length))
                        let resT = await fetch_http({
                            url: urlT,
                            method: 'get'
                        })
                        document.getElementById('relay-detail-tbody').innerHTML = ''
                        if (resT.code == 200 && resT.data.length) {
                            for (let i = 0; i < resT.data.length; i++) {
                                let trElement = document.createElement("tr");
                                let tdElement1 = document.createElement("td");
                                let tdElement2 = document.createElement("td");
                                if (resT.data[i].stationNumber == 0) {
                                    tdElement1.innerText = '起点'
                                } else if (resT.data[i].stationNumber >=1 && resT.data[i].stationNumber <=10 ) {
                                    tdElement1.innerText = resT.data[i].stationNumber
                                }else if (resT.data[i].stationNumber >=11 && resT.data[i].stationNumber <=15 ) {
                                    tdElement1.innerText = 'F'+resT.data[i].stationNumber%10
                                }else if (resT.data[i].stationNumber == 19) {
                                    tdElement1.innerText = 'S'
                                }
                                else if (resT.data[i].stationNumber == 20) {
                                    tdElement1.innerText = 'MO'
                                }
                                else if (resT.data[i].stationNumber == 99) {
                                    tdElement1.innerText = '终点'
                                }
                                resT.data[i].clockTime.split('T')

                                tdElement2.innerText = resT.data[i].clockTime.split('T')[0] + " " + resT.data[i].clockTime.split('T')[1]
                                trElement.appendChild(tdElement1)
                                trElement.appendChild(tdElement2)
                                document.getElementById('relay-detail-tbody').appendChild(trElement)
                            }
                        }

                        //查询队伍的接力人员
                        let url = new URL(BASE_URL+'/team/selectAtheleByTId')
                        url.searchParams.set("teamId", event.data.split('接力队伍id:')[1])
                        url.searchParams.set("projectId", projectId)
                        let res = await fetch_http({
                            url: url,
                            method: 'get'
                        });

                        document.getElementById('relay-team-tbody').innerHTML = ''
                        if (res.code == 200 && res.data.length) {
                            for (let i = 0; i < res.data.length; i++) {
                                let trElement = document.createElement("tr");
                                let tdElement1 = document.createElement("td");
                                let tdElement2 = document.createElement("td");
                                let tdElement3 = document.createElement("td");
                                let tdElement4 = document.createElement("td");
                                tdElement1.innerText = res.data[i].name;
                                tdElement2.innerText = res.data[i].tpCard;
                                tdElement3.innerText = res.data[i].number;
                                tdElement4.innerText = res.data[i].sequence;
                                trElement.appendChild(tdElement1)
                                trElement.appendChild(tdElement2)
                                trElement.appendChild(tdElement3)
                                trElement.appendChild(tdElement4)
                                document.getElementById('relay-team-tbody').appendChild(trElement)
                            }
                        }

                    } else {
                        let url1 = new URL(BASE_URL+'/grade/startGameSearchOnlyPerson')
                        url1.searchParams.set("gradeId", event.data.substring(5, event.data.length))
                        let res1 = await fetch_http({
                            url: url1,
                            method: 'get'
                        })

                        if (res1.code == 200 && res1.data != null) {
                            document.getElementById("detailName").innerText = res1.data.name
                            document.getElementById("detailCard").innerText = res1.data.card
                            document.getElementById("detailNumber").innerText = res1.data.number
                            document.getElementById("detailGroup").innerText = res1.data.group
                            document.getElementById("detailUnit").innerText = res1.data.unit
                            if (res1.data.unit == '无单位') {
                                document.getElementById("detailPhone").innerText = res1.data.phone
                            } else {
                                document.getElementById("detailPhone").innerText = res1.data.unitPhone
                            }
                            document.getElementById("detailRoute").innerText = res1.data.route
                            document.getElementById("detailTime").innerText = res1.data.time


                            let url = new URL(BASE_URL+'/details/getDetailsByGId')
                            url.searchParams.set("gradeId", event.data.substring(5, event.data.length))
                            let res = await fetch_http({
                                url: url,
                                method: 'get'
                            })
                            document.getElementById('person-detail-tbody').innerHTML = ''
                            if (res.code == 200 && res.data.length) {
                                for (let i = 0; i < res.data.length; i++) {
                                    let trElement = document.createElement("tr");
                                    let tdElement1 = document.createElement("td");
                                    let tdElement2 = document.createElement("td");
                                    if (res.data[i].stationNumber == 0) {
                                        tdElement1.innerText = '起点'
                                    } else if (res.data[i].stationNumber >=1 && res.data[i].stationNumber <=10 ) {
                                        tdElement1.innerText = res.data[i].stationNumber
                                    }else if (res.data[i].stationNumber >=11 && res.data[i].stationNumber <=15 ) {
                                        tdElement1.innerText = 'F'+res.data[i].stationNumber%10
                                    }else if (res.data[i].stationNumber == 19) {
                                        tdElement1.innerText = 'S'
                                    }
                                    else if (res.data[i].stationNumber == 20) {
                                        tdElement1.innerText = 'MO'
                                    }
                                    else if (res.data[i].stationNumber == 99) {
                                        tdElement1.innerText = '终点'
                                    }
                                    res.data[i].clockTime.split('T')
                                    tdElement2.innerText = res.data[i].clockTime.split('T')[0] + " " + res.data[i].clockTime.split('T')[1]
                                    trElement.appendChild(tdElement1)
                                    trElement.appendChild(tdElement2)
                                    document.getElementById('person-detail-tbody').appendChild(trElement)
                                }
                            }

                        }
                    }



                } else {
                    var makeCardMsg = document.getElementById('makeCardMsg')
                    makeCardMsg.innerText = event.data
                }

                if(unTerminal<=0){
                    socket.close()
                }

            }

            socket.onclose = async function () {
                await closePort()
                socket = null
                
                var makeCardBtn = document.getElementById('makeCardBtn')
                var makeCardMsg = document.getElementById('makeCardMsg')
                makeCardBtn.onclick = websocketConnect
                makeCardBtn.innerText = "开始录入"
                makeCardBtn.className = "btn btn-primary"
                makeCardMsg.style.display = 'none'

            }

            socket.onerror = function () {
                socket.close()
            }

        }

        //关闭websocket
        async function closeWebsocket() {
            //断开连接并关闭串口,改变按钮状态
            socket.close()
        }

        //串口通信打开请求
        async function openPort() {
            let url = new URL(BASE_URL+'/cardWebsocket/openGradePort');
            url.searchParams.set("projectId", projectId)
            url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"))
            url.searchParams.set("isRelay", isRelay);
            url.searchParams.set("project", project);
            let res = await fetch_http({
                url: url,
                method: 'get'
            })
            return res
        }

        //串口通信关闭请求
        async function closePort() {
            let url = new URL(BASE_URL+'/cardWebsocket/closePort')
            let res = await fetch_http({
                url: url,
                method: 'get',
            })
            return res
        }

        async function printGrade(){
            let btn=document.getElementById('pGrade')
            btn.innerText="打印中"
            btn.disabled='disabled'
            let url;
            if(!isRelay){
                url = new URL(BASE_URL+'/print/printPersonGrade');
                url.searchParams.set("projectId", projectId)
                url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"))
                url.searchParams.set("project", project);
                url.searchParams.set("cardId", cardId);
            }else{
                url = new URL(BASE_URL+'/print/printTeamGrade');
                url.searchParams.set("projectId", projectId)
                url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"))
                url.searchParams.set("project", project);
                url.searchParams.set("teamId", teamId);
            }
            
            let res = await fetch_http({
                url: url,
                method: 'get'
            })

            if(res.code==200){
                btn.innerText="打印小票"
                btn.disabled=''
            }else{
                btn.innerText="打印小票"
                btn.disabled=''
                alert("打印失败！请连接打印机")
            }
        }
    </script>
</body>

</html>